/**
 * @description 加入购物车
 * @author jingyujie
 * @date 2020-02-22 上午10:34:09
 */
'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ' + event)
  
  // event.num = 5
  // event.product_id = "0442d08c-426b-4c99-840a-c8c17bc49c14";
  event.user_id = "1"
  if (event.user_id == '' || !event.user_id) {
  	return {
  		success: false,
  		code: -1,
  		msg: '参数错误，缺少用户id'
  	}
  }
  if (event.num == '' || !event.num) {
  	event.num = 1;
  }
  if (event.product_id == '' || !event.product_id) {
	  return {
	  	success: false,
	  	code: -1,
	  	msg: '参数错误，缺少字段product_id参数'
	  }
  }
  let productInfo = await db.collection('product').where({
  	_id: event.product_id
  }).get()
  if(productInfo.data.length == 0){
	  await db.collection('cart').where({"product_id":event.product_id}).remove();
	  return {
	  	success: false,
	  	code: -1,
	  	msg: '未查询到该商品信息'
	  }
  }
  
  // 根据商品id查询是否已存在购物车中，存在则num+1更新，不存在则num=1新增
  let res = await db.collection('cart').where({
  	'user_id': event.user_id,
	'product_id': event.product_id
  }).get()
  let cartRes;
  let currentTime = new Date().getTime();
  if (!res.data || res.data.length === 0) {
  	// 暂无该商品，新增
	cartRes = await db.collection('cart').add({
		"user_id":event.user_id,
		"product_id":event.product_id,
		"num":event.num,
		"create_time":currentTime,
		"update_time": currentTime
	})
  }else{
	  let tempCart = res.data[0];
	  cartRes = await db.collection('cart').doc(tempCart._id).update({
		  "num":tempCart.num+event.num,
		  "update_time": currentTime
	  })
  }
  
  console.log("************************华丽的分割线（以下为获取购物车列表）************************")
  // 获取所有购物车数据
  let allRes = await db.collection('cart').where({
  	'user_id': event.user_id
  }).orderBy("create_time","desc").get()
  if(allRes.data.length == 0){
	  return {
	  	success: false,
	  	code: -1,
	  	msg: '服务器内部错误'
	  }
  }
  
  let cartList = allRes.data;
  let productIds = new Array();
  cartList.map(o => productIds.push(o.product_id))
  console.log("获取商品相关信息：" + JSON.stringify(productIds))
  // 获取商品相关信息
  const dbCmd = db.command;
  let productRes = await db.collection('product').where({
  	_id: dbCmd.in(productIds)
  }).get()
  let productList = productRes.data;
  console.log("productList:" + JSON.stringify(productList))
  let productMap = new Map();
  productList.map(o => {
  	productMap.set(o._id, o);
  })
  console.log("productMap:" + JSON.stringify(productMap.size))
  // 设置购物车信息
  cartList = await cartList.map(o=>{
  	let product = productMap.get(o.product_id);
	if(product){
		o.product_code = product.product_code
		o.product_name = product.product_name
		o.sale_price = product.sale_price
		o.book_price = product.book_price
		o.primary_img = product.primary_img
		o.publish_status = product.publish_status
	}
  	return o;
  })
  // 设置商品信息
  if (allRes.id || allRes.affectedDocs >= 1) {
  	return {
  		success: true,
  		code: 0,
  		msg: '添加成功',
  		data: cartList
  	}
  }
  return {
  	success: false,
  	code: -1,
  	msg: '服务器内部错误'
  }
};
